import { Dispatch } from 'redux'
import axios from 'axios'

const initState: State = {
	list: [],
}

export interface ListItemState {
	'key': string,
	'title': string,
	"desc": string,
	"tel": number,
	"address": string,
	'avator': string,
}

export interface State {
	list: ListItemState[]
}

const SET_LIST = 'SET_LIST'


export function fethList() {
	return async (dispatch: Dispatch) => {
		const resp = await axios.get('/api/list')
		dispatch({ type: 'SET_LIST', payload: resp.data.data })
	}
}

export function deleteList(key: string) {
	return async (dispatch: Dispatch) => {
		const resp = await axios.post('/api/delete', { key });
		dispatch(fethList() as any)
	}
}

export function editList(item: ListItemState) {
	return async (dispath: Dispatch) => {
		const resp = await axios.post('/api/edit', { item });
		dispath(fethList() as any)
	}
}

interface FetchListAction {
	type: typeof SET_LIST,
	payload: ListItemState[]
}

type ActionState = FetchListAction


const reducer = (state = initState, action: ActionState) => {
	const { type } = action
	switch (type) {
		case 'SET_LIST':
			return {
				...state,
				list: action.payload
			}
		default:
			return state;
	}
}

export default reducer